package org.springblade.modules.serial;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;


@Configuration
public class NettyServerConfig {

    @Bean
    public EventLoopGroup bossGroup() {
		// 假设有8个CPU核心
		int cores = Runtime.getRuntime().availableProcessors(); // 获取CPU核心数
		EventLoopGroup bossGroup = new NioEventLoopGroup(cores);
		EventLoopGroup workerGroup = new NioEventLoopGroup(2 * cores); // 可以根据需要调整这个倍数
        return new NioEventLoopGroup(cores);
    }

    @Bean
    public EventLoopGroup workerGroup() {
		int cores = Runtime.getRuntime().availableProcessors(); // 获取CPU核心数

		return new NioEventLoopGroup(2 * cores);
//		return new NioEventLoopGroup();
    }

    @Bean
    @DependsOn({"bossGroup", "workerGroup"})
    public ServerBootstrap serverBootstrap(EventLoopGroup bossGroup,
										   EventLoopGroup workerGroup,
										   ChannelInitializer<SocketChannel> channelInitializer) {
        return new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(channelInitializer);
    }
}
